package com.wframe.project.jnd.controller;

import java.util.*;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.frame.util.DateConvert;
import com.google.gson.Gson;
import com.sun.org.apache.xpath.internal.operations.Mod;
import com.wframe.framework.spring.SpringContextHolder;
import com.wframe.project.jnd.entity.Integral;
import com.wframe.project.jnd.rest.util.CodeEnum;
import com.wframe.project.jnd.rest.util.SessionUser;
import com.wframe.project.jnd.services.*;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import jodd.util.collection.JoddArrayList;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.frame.common.ValidateNumber;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.metadata.wordbook.WordbookService;
import com.frame.util.SelectItem;
import com.wframe.project.jnd.extinterface.sms.SmsUtil;
import com.wframe.project.jnd.rest.util.ClientException;
import com.wframe.project.jnd.rest.util.JsonReturn;
import com.wframe.project.jnd.rest.util.WebSession;
import com.wframe.project.jnd.util.WebUtils;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用户会员
 *
 * @author lenovo
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    AddressService addressService;
    @Autowired
    CouponService couponService;
    @Autowired
    InformationService informationService;
    @Autowired
    OrderService orderService;
    @Autowired
    ProductService productService;
    @Autowired
    IntegralService integralService;
    private static final String LOGIN_AD = "LOGIN_AD";
    private static final String  PC_INTEGRAL_RULE = "PC_INTEGRAL_RULE";

    /**
     * 进入用户登录页
     *
     * @return
     */
    @RequestMapping(value = "showlogin")
    public String showlogin(Model model) {
        String result = null;
        JdataBean parm = new JdataBean();
        parm.put("code", "003004");
        try {
            StringRedisTemplate stringRedisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
            if (stringRedisTemplate != null && stringRedisTemplate.opsForValue().get(LOGIN_AD) != null) {
                String data = StringUtils.trimToEmpty(stringRedisTemplate.opsForValue().get(LOGIN_AD));
                result = SerializationUtils.deserialize(Base64.decodeBase64(data));
            } else {
                List<Map<String, Object>> results = informationService.queryInfos(parm, 1, 1).getList();
                if (results.size() == 1) {
                    result = (String) results.get(0).get("phototitle");
                    String data = Base64.encodeBase64String(SerializationUtils.serialize(result));
                    stringRedisTemplate.opsForValue().set(LOGIN_AD, data, 10, TimeUnit.MINUTES);
                }
           }
        } catch (Exception e) {

            e.printStackTrace();
//            List<Map<String,Object>> results = informationService.queryInfos(parm, 1, 1).getList();
        }
        model.addAttribute("login_ad", result);
        return "/website/user/login";
    }

    /**
     * 用户登录
     *
     * @param loginname
     * @param pwd
     * @param checkcode
     * @return
     */
    @RequestMapping(value = "login")
    public void login(String loginname, String pwd, String checkcode, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            json.putData(userService.login(loginname, pwd, checkcode, session));
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 进入注册页面
     *
     * @param type
     * @return
     */
    @RequestMapping(value = "showregister")
    public String showregister(String type, Model model) {
        model.addAttribute("code", userService.createUserCode());
        if ("account".equals(type)) {
            return "/website/user/register_account";
        }

        return "/website/user/register";
    }

    /**
     * 用户注册
     *
     * @param loginname
     * @param pwd
     * @param smscode
     * @return
     */
    @RequestMapping(value = "register")
    public void register(String loginname, String mobile, String pwd, String smscode, String regtype, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if ("phone".equals(regtype)) {
                json.putData(userService.registerByPhone(mobile, pwd, smscode, UserService.UserSourceEnum.PC.ordinal()));
            } else if ("account".equals(regtype)) {
                json.putData(userService.registerByAccount(loginname, mobile, pwd, smscode, UserService.UserSourceEnum.PC.ordinal()));
            }
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }


    /**
     * 用户注销
     *
     * @param session
     * @param response
     */
    @RequestMapping(value = "loginout")
    public void loginout(HttpSession session, HttpServletResponse response) {
        WebSession.removeWbUser(session);
        JsonReturn json = new JsonReturn();
        try {
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }

    }

    /**
     * 会员中心
     *
     * @param request
     * @return
     * @throws ClientException
     */
    @RequestMapping(value = "home")
    public String home( HttpServletRequest request, HttpSession session, Model model) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            model.addAttribute("requesturl", request.getRequestURI());
            return showlogin(model);
        }
        String priceid = (String) session.getAttribute("browsepriceid");
        JdataBean user = userService.getUser(WebSession.getWbUser(request.getSession()).getUserid());
        String userid = user.getString("id");
        if (StringUtils.isNotBlank(user.getString("grade"))) {
            try {
                SelectItem item = WordbookService.getIntance().getItemName("UserGrade", user.getString("grade"));
                if (item != null) {
                    user.put("gradename", item.getText());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //会员签到
        model.addAttribute("issign",userService.queryToday( WebSession.getUserId(session))!=null);

        //缓存
        JdataBean rule = integralService.getIntegralRules();
        if(rule != null) {
            List<Integer> days = (List<Integer>) rule.get("days");
            Map<Integer, Integer> days_integral = (Map<Integer, Integer>)rule.get("days_integrals");
            String integral_rule = "";
            try {
                StringRedisTemplate stringRedisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
                if (stringRedisTemplate != null && stringRedisTemplate.opsForValue().get(PC_INTEGRAL_RULE) != null) {
                    String data = StringUtils.trimToEmpty(stringRedisTemplate.opsForValue().get(PC_INTEGRAL_RULE));
                    integral_rule = SerializationUtils.deserialize(org.apache.commons.codec.binary.Base64.decodeBase64(data));
                } else {
                    StringBuffer sb = new StringBuffer("每日签到可获得");
                    String integral_totay = rule.getString("integral_today");
                    sb.append(integral_totay).append("积分");
                    for(int i = 0 ; i < days.size() ; i++) {
                        sb.append(",累计").append(days.get(i)).append("日连续签到可获得额外获得")
                                .append(days_integral.get(days.get(i))).append("积分");
                    }
                    sb.append("；连续7日签到后重新计算累计天数。");
                    integral_rule = sb.toString();
                    String data = org.apache.commons.codec.binary.Base64.encodeBase64String(SerializationUtils.serialize(integral_rule));
                    stringRedisTemplate.opsForValue().set(PC_INTEGRAL_RULE, data, 120, TimeUnit.MINUTES);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            model.addAttribute("integral_rule", integral_rule);
            model.addAttribute("days", rule.get("days"));
            model.addAttribute("integral_today", rule.get("integral_today"));
            model.addAttribute("days_integrals" , JSON.toJSON(days_integral));


        }

        JdataBean newsTotal = informationService.queryStationnewsTotal(userid, user.getString("grade"));
        if (newsTotal != null) {
            user.put("newstotal", newsTotal.getString("total"));
        }
        JdataBean stat = userService.statUserPro(userid, UserService.UserSourceEnum.PC.ordinal());
        user.put("couponcount", stat.getString("couponnum"));
        model.addAttribute("user", user.getDataMap());


        //会员最近订单信息
        JdataBean parms = new JdataBean();
        parms.put("userid", user.getString("id"));
        int pagesize = 1;
        int pageno = 1;
        PageResult orderResult = orderService.queryOrders(parms, pagesize, pageno);
        List<HashMap<String, Object>> list = orderResult.getList();
        if (list.size() != 0) {
            HashMap<String, Object> order = list.get(0);
            List<JdataBean> statussum = orderService.queryStatusCount(userid);
            if (statussum.size() != 0) {
                for (JdataBean status : statussum) {
                    int orderstatus = status.getInt("status");
                    switch (orderstatus) {
                        case 1:
                            order.put("status1", status.getString("statussum"));
                            break;
                        case 3:
                            order.put("status3", status.getString("statussum"));
                            break;
                        case 7:
                            order.put("status7", status.getString("statussum"));
                            break;
                        case 11:
                            order.put("status11", status.getString("statussum"));
                            break;
                        default:
                            break;
                    }

                }
            }
            model.addAttribute("order", order);
        }

        //会员推荐商品
        JdataBean maylike = new JdataBean();
        int size = 8;
        int pno = 1;
        PageResult maylikes = productService.maylike(priceid, size, pno);
        productService.queryPricegrade(userid, maylikes.getList());//价格等级
        List<Map<String, Object>> likelist = new ArrayList<>();
        for (int i = 0; i < maylikes.getList().size(); i++) {
            JdataBean bean = (JdataBean) maylikes.getList().get(i);
            likelist.add(bean.getDataMap());
        }
        if (likelist.size() < 8) {
            int size2 = size - likelist.size();
            PageResult maylikes2 = productService.maylike(null, size2, pno);
            for (int i = 0; i < maylikes2.getList().size(); i++) {
                JdataBean bean = (JdataBean) maylikes2.getList().get(i);
                likelist.add(bean.getDataMap());
            }
        }
        maylike.put("likelist", likelist);
        model.addAttribute("maylike", maylike.getDataMap());

        return "/website/user/home";
    }

    /**
     * 账号管理
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "manage")
    public String manage(HttpServletRequest request, Model model) {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            model.addAttribute("requesturl", request.getRequestURI());
            return showlogin(model);
        }
        JdataBean user = userService.getUser(WebSession.getWbUser(request.getSession()).getUserid());
        if (StringUtils.isNotBlank(user.getString("grade"))) {
            try {
                SelectItem item = WordbookService.getIntance().getItemName("UserGrade", user.getString("grade"));
                if (item != null) {
                    user.put("gradename", item.getText());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        model.addAttribute("user", user.getDataMap());
        return "/website/user/manage";
    }

    @RequestMapping(value = "showchangephone")
    public String showchangephone(HttpServletRequest request, Model model) {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            model.addAttribute("requesturl", request.getRequestURI());
            return showlogin(model);
        }
        JdataBean user = userService.getUser(WebSession.getWbUser(request.getSession()).getUserid());
        model.addAttribute("user", user.getDataMap());
        return "/website/user/changePhone";
    }

    /**
     * 修改用户基本信息
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "editsave")
    public void editsave(HttpServletRequest request, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            WebSession.checkLogin(request.getSession());
            JdataBean parms = WebUtils.requestMapToBean(request.getParameterMap());
            String type = parms.getString("type");
            parms.remove("type");
            parms.put("id", WebSession.getWbUser(request.getSession()).getUserid());
            if ("nick".equals(type)) parms.put("title", parms.getString("nickname"));
            userService.editUser(parms);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 发送短信验证码
     *
     * @param response
     */
    @RequestMapping(value = "sendsms")
    public void sendsms(String mobile, String smstype, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if ("reg".equals(smstype)) {
                new SmsUtil().sendRegCode(mobile);
            } else if ("changephone".equals(smstype)) {
                new SmsUtil().sendChangephoneCode(mobile);
            } else if ("findpwd".equals(smstype)) {
                new SmsUtil().sendFindCode(mobile);
            }
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 验证短信验证码
     *
     * @param response
     */
    @RequestMapping(value = "checksmscode")
    public void checksmscode(String mobile, String smscode, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            json.putData(String.valueOf(new SmsUtil().smsCheck(mobile, smscode)));
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 更换手机绑定
     *
     * @param response
     */
    @RequestMapping(value = "changephone")
    public void changephone(String oldphone, String newphone, String oldsmscode, String newsmscode, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            userService.changephone(oldphone, newphone, oldsmscode, newsmscode, session);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 显示手机绑定页面
     */
    @RequestMapping(value = "showBindPhone")
    public String showBindPhone() {
        return "/website/user/bindPhone";
    }

    /**
     * 手机绑定
     *
     * @param response
     */
    @RequestMapping(value = "bindPhone")
    public void bindPhone(String phone, String smscode, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            userService.bindPhone(phone, smscode, session);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 修改密码
     *
     * @param response
     */
    @RequestMapping(value = "changepwd")
    public void changepwd(String oldpwd, String newpwd, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            userService.updatePwd(oldpwd, newpwd, session);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping(value = "showaddress")
    public String showaddress(HttpServletRequest request, Model model) {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            model.addAttribute("requesturl", request.getRequestURI());
            return showlogin(model);
        }
        JdataBean address = addressService.getCompanyAddress(WebSession.getWbUser(request.getSession()).getUserid());
        if (address != null)
            model.addAttribute("address", address.getDataMap());
        return "/website/user/address";
    }

    /**
     * 企业认证信息页面
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "certification")
    public String certification(HttpServletRequest request, Model model) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            model.addAttribute("requesturl", request.getRequestURI());
            return showlogin(model);
        }
        JdataBean user = userService.getUser(WebSession.getWbUser(request.getSession()).getUserid());
        JdataBean company = userService.getUserCompany(user.getString("id"));
        if (company != null) {
            if (StringUtils.isNotBlank(company.getString("type"))) {
                SelectItem item = WordbookService.getIntance().getItemName("CompanyType", company.getString("type"));
                if (item != null) {
                    company.put("typename", item.getText());
                }
            }
            model.addAttribute("company", company.getDataMap());
            List<Map> qullist = userService.queryCompanyQul(company.getString("id"));
            for (Map map : qullist) {
                model.addAttribute("type" + map.get("type"), map);
            }
        }
        model.addAttribute("user", user.getDataMap());
        model.addAttribute("typelist", WordbookService.getIntance().queryItem("CompanyType"));
        if (user.getInt("authstate") == 0 || "true".equals(request.getParameter("showapply"))) {
            return "/website/user/cer_apply";
        }
        return "/website/user/cer_info";
    }

    /**
     * 企业认证提交
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "savecer")
    public void savecer(HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean bean = new JdataBean();
            Map map = request.getParameterMap();
            Object[] keys = map.keySet().toArray();
            for (Object key : keys) {
                String[] vals = (String[]) map.get(key);
                bean.put(key.toString(), vals[0]);
            }
            bean.put("userid", WebSession.getWbUser(request.getSession()).getUserid());
            userService.saveCompany(bean);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }
    //我的积分
    @RequestMapping(value = "integral")
    public String integral(HttpServletRequest request, Model model, String psize,
                           String pno,String status,String timeType) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            model.addAttribute("requesturl", request.getRequestURI());
            return showlogin(model);
        }
        String userid = WebSession.getWbUser(request.getSession()).getUserid();
        //查询我的积分
        JdataBean myIntegral = integralService.queryUserIntegrals(userid);
        model.addAttribute("myIntegral", myIntegral.getDataMap());

        //查询我的积分详情
        int pagesize = 8;
        int pageno = 1;
        String dateType = "0";
        if (StringUtils.isNotBlank(psize)){
            pagesize = Integer.parseInt(psize);
        }
        if (StringUtils.isNotBlank(pno)){
            pageno = Integer.parseInt(pno);
        }
        if (StringUtils.isNotBlank(timeType)){
            dateType = timeType;
        }
        if(StringUtils.isBlank(status)) {
            status = "0";
        }
        JdataBean parms = new JdataBean();
        parms.put("status", status);
        parms.put("userid", userid);
        Date now = new Date();
        parms.put("end",now);
        if ("0".equals(dateType)) {
            parms.put("start", DateConvert.addMonth(now, -3));
        }if("1".equals(dateType)) {
            parms.put("start", DateConvert.addMonth(now, -6));
        }if ("2".equals(dateType)) {
            parms.put("start", DateConvert.addMonth(now, -12));
        }
        PageResult pr = integralService.queryIntegralList(parms, pagesize, pageno);
        model.addAttribute("integrals", pr.getList());
        model.addAttribute("status", status);
        model.addAttribute("timeType", dateType);
        if(pr.getPageCount() <= 1){
            model.addAttribute("pagehtml","");
        }else {
            model.addAttribute("pagehtml", WebUtils.toPageHtml(pr, 7));
        }

        //查询可兑换的优惠卷
        List<JdataBean> couponData = integralService.queryExchangeCoupon();
        List<Map<String, Object>> couponList = new ArrayList<>();
        for(JdataBean coupon : couponData) {
            couponList.add(coupon.getDataMap());
        }
        model.addAttribute("couponList", couponList);
        return "/website/user/integral";
    }

    /**
     * 我的积分详情
     * @param request
     * @param psize
     * @param pno
     * @param status
     * @param timeType
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "integralDetails")
    @ResponseBody
    public String integralDetails(HttpServletRequest request, String psize,
                                  String pno,String status,String timeType) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            throw new ClientException(CodeEnum.LoginOut);
        }
        int pagesize = 8;
        int pageno = 1;
        if (StringUtils.isNotBlank(psize)){
            pagesize = Integer.parseInt(psize);
        }
        if (StringUtils.isNotBlank(pno)){
            pageno = Integer.parseInt(pno);
        }
        JsonReturn json = new JsonReturn();

        JdataBean parms = new JdataBean();
        parms.put("status", status);
        parms.put("userid", WebSession.getWbUser(request.getSession()).getUserid());
        Date now = new Date();
        parms.put("end",now);
        if ("0".equals(timeType)) {
            parms.put("start", DateConvert.addMonth(now, -3));
        }if("1".equals(timeType)) {
            parms.put("start", DateConvert.addMonth(now, -6));
        }if ("2".equals(timeType)) {
            parms.put("start", DateConvert.addMonth(now, -12));
        }
        PageResult pr = integralService.queryIntegralList(parms, pagesize, pageno);
        HashMap<String, Object> map = new HashMap<>();
        map.put("integrals",pr.getList());
        map.put("pageCount",pr.getPageCount());
        if(pr.getPageCount() <= 1){
            map.put("pagehtml","");
        }else {
            map.put("pagehtml", WebUtils.toPageHtml(pr, 7));
        }
        json.putData(map);
        return json.toString();

    }
    @RequestMapping(value = "exchangeCoupon")
    @ResponseBody
    public String exchangeCoupon(HttpServletRequest request, String couponid,
                                 String pno,String status,String timeType) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            throw new ClientException(CodeEnum.LoginOut);
        }
        String userid = WebSession.getWbUser(request.getSession()).getUserid();

        JsonReturn json = new JsonReturn();
        String state = integralService.exchangeCoupon(userid, couponid, 1);
        Map<String, Object> map = new HashMap<>();
        map.put("status", state);

        //查询我的积分
        JdataBean myIntegral = integralService.queryUserIntegrals(userid);
        map.put("myIntegral", myIntegral.getDataMap());

        //查看积分明细
        int pagesize = 8;
        int pageno = 1;
        if (StringUtils.isNotBlank(pno)){
            pageno = Integer.parseInt(pno);
        }
        JdataBean parms = new JdataBean();
        parms.put("status", status);
        parms.put("userid", userid);
        Date now = new Date();
        parms.put("end",now);
        if ("0".equals(timeType)) {
            parms.put("start", DateConvert.addMonth(now, -3));
        }if("1".equals(timeType)) {
            parms.put("start", DateConvert.addMonth(now, -6));
        }if ("2".equals(timeType)) {
            parms.put("start", DateConvert.addMonth(now, -12));
        }
        PageResult pr = integralService.queryIntegralList(parms, pagesize, pageno);
        map.put("integrals",pr.getList());
        map.put("pageCount",pr.getPageCount());
        if(pr.getPageCount() <= 1){
            map.put("pagehtml","");
        }else {
            map.put("pagehtml", WebUtils.toPageHtml(pr, 7));
        }

        json.putData(map);
        return json.toString();
    }

    /**
     * 检查是否认证
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "checkauth")
    public void checkauth(HttpSession session, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                json.putData("nologin");
            } else {
                JdataBean user = userService.getUser(WebSession.getWbUser(session).getUserid());
                if (user.getInt("authstate") == 2) {
                    json.putData("ok");
                } else {
                    json.putData("noauth");
                }
            }
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 检查账号
     *
     * @param loginname
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "checkloginname")
    public void checkloginname(String loginname, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            json.putData(userService.checkloginname(loginname));
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 检查图形验证码
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "checkimgcode")
    public void checkimgcode(String code, HttpSession session, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            json.putData(ValidateNumber.checkAll(code, session));
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 找回设置新密码
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "findpwd")
    public void findpwd(String userid, String phone, String smscode, String newpwd, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            userService.findpwd(userid, phone, smscode, newpwd);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping(value = "helps")
    public String helps(Integer pno, Model model) {
        String channelcode = "002008";
        JdataBean parms = new JdataBean();
        parms.put("code", channelcode);
        int no = 1;
        if (pno != null) no = pno.intValue();
        PageResult pr = informationService.queryInfos(parms, 20, no);
        model.addAttribute("channelcode", channelcode);
        model.addAttribute("list", pr.getList());
        model.addAttribute("pagehtml", WebUtils.toPageHtml(pr, 7));
        return "/website/user/helps";
    }

    /**
     * 站内消息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "stationnews")
    public String stationnews(String pno, HttpServletRequest request, Model model) {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "redirect:/user/showlogin";
        }
        String userid = WebSession.getWbUser(request.getSession()).getUserid();
        JdataBean user = userService.getUser(userid);
        int pageno = 1;
        if (StringUtils.isNotBlank(pno)) pageno = Integer.parseInt(pno);
        PageResult pr = informationService.queryStationnews(userid, user.getString("grade"), 20, pageno);
        informationService.setStationnewsRead(userid);
        model.addAttribute("list", pr.getList());
        model.addAttribute("pagehtml", WebUtils.toPageHtml(pr, 7));
        return "/website/user/stationnews";
    }

    /**
     * 检查账号信息
     *
     * @param response
     */
    @RequestMapping(value = "checkAccount")
    public void checkAccount(String loginname, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean user = userService.getUserByAccount(loginname);
            JdataBean data = new JdataBean();
            data.put("exist", String.valueOf(user != null));
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 意见反馈
     */
    @RequestMapping(value = "feedbackshow")
    public String feedbackshow(HttpSession session, HttpServletRequest request, Model model) {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            model.addAttribute("requesturl", request.getRequestURI());
            return showlogin(model);
        }
        if (WebSession.checkLoginStatus(session)) {
            JdataBean user = userService.getUser(WebSession.getWbUser(session).getUserid());
            model.addAttribute("phone", user.getString("phone"));
        }
        return "/website/user/feedbackWrite";
    }

    /**
     * 意见反馈提交
     *
     * @param response
     */
    @RequestMapping(value = "feedbackwrite")
    public void feedbackwrite(String phone, String content, @RequestParam(value = "photoids[]", required = false) String[] photoids, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean bean = new JdataBean();
            if (WebSession.checkLoginStatus(session)) {
                bean.put("userid", WebSession.getWbUser(session).getUserid());
            }

            JdataBean user = userService.getUser(WebSession.getWbUser(session).getUserid());
            String loginname = user.getString("loginname");
            bean.put("loginname", loginname);
            bean.put("type", 2);     //添加标识2标示pc端添加
            bean.put("phone", phone);
            bean.put("content", content);
            if (photoids != null) {
                bean.put("photo", photoids[0]);//第一张设置为主图片
                bean.put("photoids", photoids);
            }

            userService.writefeedback(bean);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping("/PCFeedbackList")
    public String Entrance() {
        return "/website/user/feedbackWrite";
    }

    /**
     * PC意见反馈
     *
     * @param phone
     * @param content
     * @param photoids
     * @param response
     */


    @RequestMapping(value = "PCFeedback")
    @ResponseBody
    public void PCFeedback(String phone, String content, @RequestParam(value = "photoids[]", required = false) String[] photoids, HttpServletResponse response, HttpSession session) {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean bean = new JdataBean();
            String loginname = "";
            if (WebSession.checkLoginStatus(session)) {
                JdataBean user = userService.getUser(WebSession.getWbUser(session).getUserid());
                loginname = user.getString("loginname");
            }
            bean.put("loginname", loginname);
            bean.put("type", 2);     //添加标识2标示pc端添加
            bean.put("phone", phone);
            bean.put("content", content);
            if(photoids !=null){
                bean.put("photo", photoids[0]);//第一张设置为主图片
                bean.put("photoids", photoids);
            }
            userService.PCFeedback(bean);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * PC会员签到
     * @param response
     * @param session
     */
    @RequestMapping(value = "/home/sign")
    public void Sign(HttpServletResponse response, HttpSession session) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean bean = new JdataBean();
            if (WebSession.checkLoginStatus(session)) {
                bean.put("userid", WebSession.getWbUser(session).getUserid());
            }
            String userid = WebSession.getUserId(session);
            JdataBean record = userService.queryToday(userid);
            if(record == null) {
                //查询积分规则
                JdataBean rule = integralService.getIntegralRules();
                List<Integer> days = (List<Integer>) rule.get("days");
                Map<Integer, Integer> days_integrals = (Map<Integer, Integer>)rule.get("days_integrals");
                JdataBean sign = userService.getquerywbsign(userid);
                int signcount = 0;
                int integral = rule.getInt("integral_today");
                if (sign != null) {
                    signcount = sign.getInt("signcount");
                    signcount++;
                    for (int i = 0, size = days.size() ; i < size ; i++) {
                        if (signcount == days.get(i)) {
                            integral += days_integrals.get(days.get(i));
                            break;
                        }
                    }
                    if (signcount == 7) {
                        signcount = 0;
                    }
                }else {
                    signcount++;
                    for (int i = 0, size = days.size() ; i < size ; i++) {
                        if (signcount == days.get(i)) {
                            integral += days_integrals.get(days.get(i));
                            break;
                        }
                    }
                }

                bean.put("platform", 1);//平台
                bean.put("signcount", signcount);//签到次数
                bean.put("integral", integral);//签到积分
                JdataBean integralData = new JdataBean();
                integralData.put("type", Integral.Type.LOGIN.ordinal());
                integralData.put("content", "签到获得积分");
                userService.saveSignRecord(bean);
                integralData.put("platform", 1);
                integralService.updateUserIntegral( userid, String.valueOf(integral),integralData);

            }
            JdataBean myIntegral = integralService.queryUserIntegrals(userid);
            json.putData(myIntegral.getDataMap());
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * PC点击签到
     * @param response
     * @param session
     */
    @RequestMapping(value = "/signStatus")
    public void signStatus(HttpServletResponse response,HttpSession session){
        JsonReturn json = new JsonReturn();
        try{
            String userId = WebSession.getUserId(session);
            int signcount = 0;
            JdataBean sign = userService.querysigncount(userId);
            Map data = new HashMap();
            if(sign != null) {
                signcount=sign.getInt("signcount");

            }
            data.put("signcount",signcount );
            data.put("issign",userService.queryToday(userId)!=null);
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
        }catch (Exception e){
            WebUtils.responseWrite(response,json.toErrorString(this.getClass(),e));
        }
    }



    /**
     * 用户待办消息数
     *
     * @param response
     */
    @RequestMapping(value = "userNoNum")
    public void userNoNum(HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            int cartnum = 0;//购物车数量
            int newnum = 0;//未读消息数
            if (WebSession.checkLoginStatus(session)) {
                cartnum = orderService.statCartnum(WebSession.getWbUser(session).getUserid());
                newnum = informationService.statNonews(WebSession.getWbUser(session).getUserid());
            }
            JdataBean data = new JdataBean();
            data.put("cartnum", cartnum);
            data.put("newsnum", newnum);
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 侧边栏用户中心
     */
    @RequestMapping(value = "center")
    public void showCenter(HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            int integral = 0;//用户积分
            int couponnum = 0;//优惠券数量
            int newnum = 0;//未读消息数
            Map data = new HashMap();
            SessionUser sessionUser = WebSession.getWbUser(session);
            if (sessionUser != null) {
                String userid = sessionUser.getUserid();
                JdataBean user = userService.getUser(userid);
                data.putAll(user.getDataMap());
                couponnum = couponService.queryCoupon(userid, 1, UserService.UserSourceEnum.PC.ordinal(), 1, 1).getPageCount();
                newnum = informationService.statNonews(userid);
            }

            data.put("integral", integral);
            data.put("couponnum", couponnum);
            data.put("newsnum", newnum);
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

}
